package response

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// Response 统一响应结构
type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

// PageResult 分页响应结构
type PageResult struct {
	List       interface{} `json:"list"`
	Total      int64       `json:"total"`
	Page       int         `json:"page"`
	PageSize   int         `json:"pageSize"`
	TotalPages int         `json:"totalPages"`
}

// 响应状态码
const (
	SUCCESS               = 200
	ERROR                 = 500
	INVALID_PARAMS        = 400
	UNAUTHORIZED          = 401
	FORBIDDEN             = 403
	NOT_FOUND             = 404
	INTERNAL_SERVER_ERROR = 500
	SERVICE_UNAVAILABLE   = 503
)

// Success 成功响应
func Success(c *gin.Context) {
	c.JSON(http.StatusOK, Response{
		Code:    SUCCESS,
		Message: "success",
	})
}

// SuccessWithData 成功响应（带数据）
func SuccessWithData(c *gin.Context, data interface{}) {
	c.JSON(http.StatusOK, Response{
		Code:    SUCCESS,
		Message: "success",
		Data:    data,
	})
}

// SuccessWithMessage 成功响应（带消息）
func SuccessWithMessage(c *gin.Context, message string) {
	c.JSON(http.StatusOK, Response{
		Code:    SUCCESS,
		Message: message,
	})
}

// SuccessWithPage 成功响应（分页数据）
func SuccessWithPage(c *gin.Context, list interface{}, total int64, page, pageSize int) {
	totalPages := int(total) / pageSize
	if int(total)%pageSize > 0 {
		totalPages++
	}

	c.JSON(http.StatusOK, Response{
		Code:    SUCCESS,
		Message: "success",
		Data: PageResult{
			List:       list,
			Total:      total,
			Page:       page,
			PageSize:   pageSize,
			TotalPages: totalPages,
		},
	})
}

// Error 错误响应
func Error(c *gin.Context, message string) {
	c.JSON(http.StatusOK, Response{
		Code:    ERROR,
		Message: message,
	})
}

// ErrorWithCode 错误响应（带状态码）
func ErrorWithCode(c *gin.Context, code int, message string) {
	c.JSON(http.StatusOK, Response{
		Code:    code,
		Message: message,
	})
}

// BadRequest 请求参数错误
func BadRequest(c *gin.Context, message string) {
	c.JSON(http.StatusOK, Response{
		Code:    INVALID_PARAMS,
		Message: message,
	})
}

// Unauthorized 未授权
func Unauthorized(c *gin.Context, message string) {
	c.JSON(http.StatusOK, Response{
		Code:    UNAUTHORIZED,
		Message: message,
	})
}

// Forbidden 无权限
func Forbidden(c *gin.Context, message string) {
	c.JSON(http.StatusOK, Response{
		Code:    FORBIDDEN,
		Message: message,
	})
}

// NotFound 资源不存在
func NotFound(c *gin.Context, message string) {
	c.JSON(http.StatusOK, Response{
		Code:    NOT_FOUND,
		Message: message,
	})
}

// InternalServerError 服务器错误
func InternalServerError(c *gin.Context, message string) {
	c.JSON(http.StatusOK, Response{
		Code:    INTERNAL_SERVER_ERROR,
		Message: message,
	})
}
